<template>
    <div class="module-wrapper">
        <DataGrid
            :auto-load="autoLoad"
            row-key="id"
            border
            default-expand-all
            ref="dataGridRef"
            :pagination="false"
            :tree-props="treeProps"
        >
            <template #toolbar-search>
                <div class="query-from-box">
                    <el-form>
                        <el-form-item>
                            <el-input v-model="queryData.queryName" placeholder="模型名称/标识符" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="queryData.isComponent" placeholder="用途" clearable>
                                <el-option v-for="(value, key) in usageType" :label="value" :key="key" :value="key" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <template #toolbar-operation>
                <el-button size="small" type="primary" @click="operCollect('添加')">添加</el-button>
                <el-button :icon="Guide" circle @click="$emit('changeMode')" />
            </template>
            <el-table-column label="模型名称" width="280" show-overflow-tooltip fixed>
                <template #default="scope">
                    <el-button link type="primary" @click="operCollect('查看', scope.row)"
                        >{{ scope.row.displayName
                        }}{{
                            detailData?.componentNum && !scope.row.depth ? `（${detailData?.componentNum}）` : ''
                        }}</el-button
                    >
                </template>
            </el-table-column>
            <el-table-column prop="objectName" label="标识符" show-overflow-tooltip />
            <el-table-column prop="slot" label="槽号" />
            <el-table-column prop="modifierType" label="模型性质">
                <template #default="scope">
                    {{ modifierType[scope.row.modifierType] }}
                </template>
            </el-table-column>
            <el-table-column label="模型用途">
                <template #default="scope">
                    {{ usageType[scope.row.isComponent] }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="60" fixed="right">
                <template #default="scope">
                    <el-button link type="danger" @click="operCollect('删除', scope.row)" v-if="scope.row.depth === 1">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </DataGrid>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { modelThingService } from '@great/services';
import { showPopupBox } from '@great/utils';
import type { SysMetadataObject, SysThingObjectTreeVo } from '@great/services';
import { modifierType } from '@/utils/constant';
import ModuleAddModal from './ModuleAddModal.vue';
import { DataGrid, type DataGridInstance } from '@great/components';
import { useRouter } from 'vue-router';
import { Guide } from '@element-plus/icons-vue';

enum usageType {
    true = '组件',
    false = '产品'
}
const props = defineProps<{
    detailData?: SysMetadataObject;
}>();
const $emit = defineEmits<{
    (e: 'changeMode'): void;
}>();
const initModelDetail: any = inject('initModelDetail');
const router = useRouter();

const treeProps = reactive({
    children: 'components'
});
// 查询条件
const queryData = ref({
    objectName: props.detailData?.objectName,
    queryName: '',
    isComponent: null
});
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async () => {
        const res = await modelThingService.getComponentList({
            ...queryData.value
        });
        return { data: addDepthToTree(res.data) };
    }
});
// 递归为每个节点添加 depth 属性
const addDepthToTree = (data, depth = 0) => {
    return data.map(node => {
        // 为当前节点添加 depth
        const nodeWithDepth = { ...node, depth };
        // 递归处理子节点，层级 +1
        if (node.components && node.components.length > 0) {
            nodeWithDepth.components = addDepthToTree(node.components, depth + 1);
        }
        return nodeWithDepth;
    });
};
/**
 * 操作收集
 * @param type 操作类型
 * @param row 操作行数据
 */
const operCollect = (type: string, row?: SysThingObjectTreeVo) => {
    switch (type) {
        case '添加':
            showPopupBox(ModuleAddModal, {
                getList: (): any => {
                    dataGridRef.value?.refresh();
                    initModelDetail();
                },
                detailData: props.detailData as SysMetadataObject
            });
            break;
        case '查看': {
            router.push({
                name: 'model-thing-detail',
                params: {
                    id: row?.objectId
                }
            });
            break;
        }
        case '删除': {
            let tip = `是否确认删除模型 ${row?.displayName} ？`;
            if (row && row.components && row.components.length) {
                tip = `该模型及其下级模型，将一同被删除，确认删除？`;
            }
            ElMessageBox.confirm(tip, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    await modelThingService.delComponent([row?.id as number]);
                    ElNotification({
                        title: '删除成功！',
                        type: 'success'
                    });
                    dataGridRef.value?.refresh();
                    initModelDetail();
                })
                .catch(() => {});
            break;
        }
    }
};
</script>
<style scoped lang="scss">
.module-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
}
</style>
